package com.jinlejia.erp.ui.house.prospect;

import android.app.Activity;
import android.content.Context;
import android.content.Intent;
import android.os.Bundle;
import android.text.TextUtils;
import android.view.View;

import androidx.appcompat.app.AppCompatActivity;
import androidx.databinding.DataBindingUtil;

import com.jinlejia.erp.R;
import com.jinlejia.erp.databinding.ActivityProspectIndexBinding;
import com.jinlejia.erp.ui.common.CommonDialog;
import com.jinlejia.erp.ui.common.ProgressDialog;
import com.jinlejia.erp.ui.house.prospect.bean.ReasonBean;
import com.jinlejia.erp.ui.house.prospect.bean.SurveyPictureBean;
import com.jinlejia.erp.ui.house.prospect.dialog.ProspectReasonDialog;
import com.jinlejia.erp.ui.house.prospect.dialog.ProspectSelectHouseTypeDialog;
import com.jinlejia.erp.widget.prospect.ProspectRadioImageButton;
import com.weight.CustomToast;

import java.util.ArrayList;
import java.util.List;
import java.util.Map;

/**
 * 实勘图片上传引导页
 */
public class ProspectIndexActivity extends AppCompatActivity implements ProspectRadioImageButton.ProspectRadioImageButtonListener {

    private Context mContext = ProspectIndexActivity.this;

    private String houseSourceCode; //房源编码
    private String houseSourceType; //房源类型
    private String houseType;   //房屋户型
    private String houseUsage;  //房屋用途
    private int pageType; //跳页选项
    private String rejectReason;    //驳回原因
    private boolean isReason;

    private int oldRoomNum,oldDrawingNum,oldToiletNum,oldKitchenNum;
    private int imageShowType;
    private String applyCode;

    private int selectHouseUsage = -1; //用户选择的房屋用途
    private Helper helper;
    private SurveyPictureBean tempSource; //缓存服务器传递过来的数据


    //住宅室厅卫厨
    private ArrayList<Map<String,Object>> residences = new ArrayList<>();
    private ArrayList<Map<String,Object>> residencet = new ArrayList<>();
    private ArrayList<Map<String,Object>> residencew = new ArrayList<>();
    private ArrayList<Map<String,Object>> residencec = new ArrayList<>();
    //公寓室厅卫厨
    private ArrayList<Map<String,Object>> apartments = new ArrayList<>();
    private ArrayList<Map<String,Object>> apartmentt = new ArrayList<>();
    private ArrayList<Map<String,Object>> apartmentw = new ArrayList<>();
    private ArrayList<Map<String,Object>> apartmentc = new ArrayList<>();
    //别墅室厅卫厨
    private ArrayList<Map<String,Object>> villas = new ArrayList<>();
    private ArrayList<Map<String,Object>> villat = new ArrayList<>();
    private ArrayList<Map<String,Object>> villaw = new ArrayList<>();
    private ArrayList<Map<String,Object>> villac = new ArrayList<>();
    //顶替理由
    private List<ReasonBean> reasonslist;

    private ActivityProspectIndexBinding binding;
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        binding = DataBindingUtil.setContentView(this,R.layout.activity_prospect_index);
        binding.reasonsLayout.setOnClickListener(v->showReasonDialog());
        binding.toolbarBackImageView.setOnClickListener(v->finishActivity());
        binding.residentialButton.setOnClickListener(this::changeFocus);
        binding.apartmentButton.setOnClickListener(this::changeFocus);
        binding.villaButton.setOnClickListener(this::changeFocus);
        binding.shopButton.setOnClickListener(this::changeFocus);
        binding.officeButton.setOnClickListener(this::changeFocus);
        binding.warehouseButton.setOnClickListener(this::changeFocus);
        binding.chooseHouseTypeLayout.setOnClickListener(v->chooseHouseType());

        helper = Helper.init(this);
        initData();
        Bundle bundle = getIntent().getExtras();
        if (bundle!=null){
            this.pageType = bundle.getInt(Type.PARAM.PAGE_TYPE); //跳页 1新增 2修改 3补充
            this.houseSourceCode = bundle.getString(Type.PARAM.HOUSE_SOURCE_CODE); //房源编码
            this.isReason = bundle.getBoolean(Type.PARAM.REASON);
            this.houseSourceType = bundle.getString(Type.PARAM.HOUSE_SOURCE_TYPE); //房源类型
            this.houseType = bundle.getString(Type.PARAM.HOUSE_TYPE); //房屋户型
            this.houseUsage = bundle.getString(Type.PARAM.HOUSE_USAGE_NAME); //房屋用途
            int usageType = helper.util().mapUsageNameToUsageType(houseUsage);
            if (helper.message().hasHouseType(usageType)){
                //将房屋户型转换为 1-2-3-4 1室2厅3卫4厨
                this.houseType = helper.util().formatHouseInfo(this.houseType).toString();
            }
            this.imageShowType = bundle.getInt(Type.PARAM.IMAGE_SHOW_TYPE); //跳转至添加图片使用
        }
        initRadioButtonListener();
        binding.toolbarTitleTextView.setText("实勘图片上传");
        helper.message().closeMessage();
        if (this.pageType ==1){ //新增
            showAddProspect();
        }else if (this.pageType ==2){ //修改
            showUpdateProspectView();
        }else if (this.pageType==3){ //补充
            showUpdateProspectView();
        }

    }

    //网络请求数据
    private void initData() {
        helper.http().prospectReason(list -> reasonslist = list, (residenceS, residenceT, residenceW, residenceC, apartmentS, apartmentT, apartmentW, apartmentC, villaS, villaT, villaW, villaC) -> {
            residences = residenceS;
            residencet = residenceT;
            residencew = residenceW;
            residencec = residenceC;
            apartments = apartmentS;
            apartmentt = apartmentT;
            apartmentw = apartmentW;
            apartmentc = apartmentC;
            villas = villaS;
            villat = villaT;
            villaw = villaW;
            villac = villaC;

        });
    }


    private void showReason(String reason){
        binding.reasonsLayout.setVisibility(View.VISIBLE);
        binding.chooseReasonTextView.setText(reason);
    }
    private ProspectReasonDialog reasonDialog;
    private void initView() {
        if (!TextUtils.isEmpty(this.rejectReason)){ //驳回原因
            helper.message().showErrorMessage(this.rejectReason);
        }
        //region 显示或隐藏 理由UI
        int reasonLayoutVisibility = this.isReason ? View.VISIBLE : View.GONE;
        binding.reasonsLayout.setVisibility(reasonLayoutVisibility);
        //endregion

        //自动选择房屋用途
        if (!TextUtils.isEmpty(houseUsage)){
            if ("商铺".equals(houseUsage)){
                binding.shopButton.setChecked(true);
            }else if ("住宅".equals(houseUsage)){
                binding.residentialButton.setChecked(true);
            }else if ("公寓".equals(houseUsage)){
                binding.apartmentButton.setChecked(true);
            }else if ("别墅".equals(houseUsage)){
                binding.villaButton.setChecked(true);
            }else if ("写字楼".equals(houseUsage)){
                binding.officeButton.setChecked(true);
            }else if (houseUsage.contains("厂房")){
                binding.warehouseButton.setChecked(true);
            }
        }
        //自动填充房屋户型
        if (!TextUtils.isEmpty(houseType) && binding.chooseHouseTypeLayout.getVisibility() != View.GONE){
            String value = helper.util().formatHouseInfo(houseType).toText();
            binding.chooseHouseTypeValueTextView.setText(value);
            binding.chooseHouseTypeValueTextView.setTag(houseType);
        }

    }


    //选择顶替理由
    public void showReasonDialog() {
        if (reasonDialog!=null){
            reasonDialog.show();
            return;
        }

        if (reasonslist != null && reasonslist.size() > 0) {
            if (reasonDialog == null) {
                reasonDialog = new ProspectReasonDialog(ProspectIndexActivity.this, reasonslist);
                reasonDialog.setListener(result -> {
                    binding.chooseReasonTextView.setText(result.getValueName());
                    binding.chooseReasonTextView.setTag(result);
                });
            }
            reasonDialog.show();
        }

    }

    //region 新增
    /**显示新增操作*/
    private void showAddProspect(){
        binding.rightButton.setVisibility(View.VISIBLE);
        binding.rightButton.setText("下一步");

        binding.rightButton.setOnClickListener(v -> {
            if (isFastClick())return;
            toProspectUploadImageActivity(null);
        });
        initView();
    }

    private boolean check(){
        if (!binding.residentialButton.isChecked() && !binding.apartmentButton.isChecked() && !binding.villaButton.isChecked()
                && !binding.shopButton.isChecked() && !binding.officeButton.isChecked() && !binding.warehouseButton.isChecked()){
            CustomToast.showToast(this, "请选择房屋用途", 1500);
            return false;
        }
        if (TextUtils.isEmpty(binding.chooseHouseTypeValueTextView.getText())
                || TextUtils.isEmpty(String.valueOf(binding.chooseHouseTypeValueTextView.getTag()))){
            if (binding.chooseHouseTypeLayout.getVisibility() == View.VISIBLE){
                CustomToast.showToast(this,"请选择户型",1500);
                return false;
            }
        }
        if (binding.reasonsLayout.getVisibility() == View.VISIBLE){
            if (TextUtils.isEmpty(binding.chooseReasonTextView.getText())){
                CustomToast.showToast(this,"请选择顶替理由",1500);
                return false;
            }
        }
        return true;
    }

    private void toProspectUploadImageActivity(SurveyPictureBean bean){
        if (!check())return;
        Intent intent = new Intent();
        intent.setClass(ProspectIndexActivity.this,ProspectUploadImageActivity.class);
        String houseType = String.valueOf(binding.chooseHouseTypeValueTextView.getTag());
        intent.putExtra(Type.PARAM.HOUSE_TYPE,houseType);
        intent.putExtra(Type.PARAM.PAGE_TYPE,this.pageType); //跳页方式
        intent.putExtra(Type.PARAM.HOUSE_USAGE_TYPE,this.selectHouseUsage); //房源用途

        intent.putExtra(Type.PARAM.HOUSE_SOURCE_CODE,this.houseSourceCode); //房源编码
        intent.putExtra(Type.PARAM.HOUSE_SOURCE_TYPE,this.houseSourceType); //房源类型
        intent.putExtra(Type.PARAM.REJECT_REASON,rejectReason);             //驳回理由
        intent.putExtra(Type.PARAM.HOUSE_APPLY_CODE,applyCode);             //实勘编码
        intent.putExtra(Type.PARAM.IMAGE_SHOW_TYPE,this.imageShowType);     //只上传图片
        intent.putExtra(Type.PARAM.HOUSE_REASON,binding.chooseReasonTextView.getText().toString()); //顶替理由
        if (bean!=null){
            intent.putExtra(Type.PARAM.HOUSE_SOURCE_INFO,bean); //房源信息
        }
        startActivityForResult(intent,20);
    }
    //endregion

    @Override
    protected void onDestroy() {
        super.onDestroy();
        if (chooseDialog!=null){
            chooseDialog.dismiss();
            chooseDialog = null;
        }
        if (helper != null){
            helper.release();
        }
    }

    public void finishActivity(){
        this.finish();
    }

    private ProgressDialog progressDialog;

    /**显示修改房源信息的UI*/
    private void showUpdateProspectView(){
        if (progressDialog==null){
            progressDialog = new ProgressDialog(this);
        }
        if (progressDialog.isShowing()){
            progressDialog.dismiss();
        }
        loadHouseSource();
        progressDialog.show();
        binding.rightButton.setText("下一步");
    }
    private void loadHouseSource(){
        helper.http().getServey(houseSourceType, houseSourceCode, bean -> {
            if (progressDialog!=null){
                progressDialog.dismiss();
            }
            if (bean==null){
                initView();
                return;
            }
            tempSource = bean.toBean();
            applyCode = bean.getApplyCode();
            rejectReason = bean.getRejectReason();
            houseUsage = bean.getPurpose(); //房屋用途
            oldRoomNum = bean.getRoom();
            oldDrawingNum = bean.getHall();
            oldKitchenNum = bean.getKitchen();
            oldToiletNum = bean.getToilet();
            houseType = helper.util().formatHouseInfo(oldRoomNum,oldDrawingNum,oldToiletNum,oldKitchenNum).toString();
            initView();
            if (!TextUtils.isEmpty(bean.getReason())){
                showReason(bean.getReason());
            }
            binding.rightButton.setOnClickListener(v -> {
                if (isFastClick())return;
                toProspectUploadImageActivity(tempSource);
            });
        });
    }

    private final int MIN_DELAY_TIME = 1000;  // 两次点击间隔不能少于1000ms
    private long lastClickTime;
    private boolean isFastClick() {
        boolean flag = true;
        long currentClickTime = System.currentTimeMillis();
        if ((currentClickTime - lastClickTime) >= MIN_DELAY_TIME) {
            flag = false;
        }
        lastClickTime = currentClickTime;
        return flag;
    }

    private void initRadioButtonListener(){
        binding.residentialButton.setListener(this);
        binding.apartmentButton.setListener(this);
        binding.villaButton.setListener(this);
        binding.shopButton.setListener(this);
        binding.officeButton.setListener(this);
        binding.warehouseButton.setListener(this);
    }
    private ProspectRadioImageButton checkButton;
    @Override
    public boolean onChecked(final ProspectRadioImageButton button) {
        if (button.equals(binding.residentialButton)){ //住宅
            selectHouseUsage = Type.USAGE_RESIDENTIAL;
        }else if (button.equals(binding.apartmentButton)){ //公寓
            selectHouseUsage = Type.USAGE_APARTMENT;
        }else if (button.equals(binding.villaButton)){ //别墅
            selectHouseUsage = Type.USAGE_VILLA;
        }else if (button.equals(binding.shopButton)){ //商铺
            selectHouseUsage = Type.USAGE_SHOP;
        }else if (button.equals(binding.officeButton)){ //写字楼
            selectHouseUsage = Type.USAGE_OFFICE;
        }else if (button.equals(binding.warehouseButton)){ //厂房
            selectHouseUsage = Type.USAGE_WAREHOUSE;
        }
        else {
            selectHouseUsage = -1;
        }
        //选择“商铺、写字楼、厂房/仓库”时，不需要录入户型
        if (button.equals(binding.shopButton) || button.equals(binding.officeButton)
                || button.equals(binding.warehouseButton)){
            binding.chooseHouseTypeLayout.setVisibility(View.GONE);
            binding.chooseHouseTypeValueTextView.setText(null);
            binding.chooseHouseTypeValueTextView.setTag(null);
        }else {
            binding.chooseHouseTypeLayout.setVisibility(View.VISIBLE);
        }
        if (checkButton==null){
            checkButton = button;
            binding.chooseHouseTypeValueTextView.setText(null);
            binding.chooseHouseTypeValueTextView.setTag(null);
            return false;
        }
        if (!button.equals(checkButton)){
            binding.chooseHouseTypeValueTextView.setText(null);
            binding.chooseHouseTypeValueTextView.setTag(null);
        }
        checkButton = button;
        if (binding.residentialButton.isChecked() || binding.apartmentButton.isChecked()
                || binding.villaButton.isChecked() || binding.shopButton.isChecked() || binding.officeButton.isChecked() || binding.warehouseButton.isChecked()) {
            if (binding.chooseHouseTypeValueTextView.getTag()!=null){
                binding.chooseHouseTypeValueTextView.setText(null);
                binding.chooseHouseTypeValueTextView.setTag(null);
            }
        }

        return false;
    }
    //region 选中某个房屋类型
    public void changeFocus(final View view){
        binding.residentialButton.setChecked(false);
        binding.apartmentButton.setChecked(false);
        binding.villaButton.setChecked(false);
        binding.shopButton.setChecked(false);
        binding.officeButton.setChecked(false);
        binding.warehouseButton.setChecked(false);
        if (view instanceof ProspectRadioImageButton){
            final ProspectRadioImageButton button = (ProspectRadioImageButton) view;
            if (pageType!=1 &&  !button.equals(checkButton)){ //修改-补充时，对用户的户型类型进行提示
                if (commonDialog != null){
                    commonDialog.dismiss();
                    commonDialog = null;
                }
                commonDialog = new CommonDialog(mContext,"警告","修改用途需要重新上传全部图片，确定修改吗？"
                        ,"确定","取消");
                commonDialog.setConfirmListener(() -> {
                    if (tempSource!=null){
                        tempSource.clear();
                        oldRoomNum =0;oldDrawingNum =0;oldToiletNum =0;oldKitchenNum=0;
                    }
                    button.setChecked(true);
                });
                commonDialog.setCancelListener(() -> {
                    if (checkButton!=null){
                        checkButton.setChecked(true);
                    }
                });
                commonDialog.show();
                return;
            }
            ((ProspectRadioImageButton) view).setChecked(true);
        }

    }
    //endregion

    //region 选择户型信息
    private ProspectSelectHouseTypeDialog chooseDialog;
    private CommonDialog commonDialog;
    public void chooseHouseType(){

        if (chooseDialog!=null){
            chooseDialog.dismiss();
            chooseDialog = null;
        }
        if (!binding.residentialButton.isChecked() && !binding.apartmentButton.isChecked() && !binding.villaButton.isChecked()
                && !binding.shopButton.isChecked() && !binding.officeButton.isChecked() && !binding.warehouseButton.isChecked()){
            CustomToast.showToast(this, "请选择房屋用途", 1500);
            return;
        }
        String text = String.valueOf(binding.chooseHouseTypeValueTextView.getTag());
        Helper.Util.HouseInfo info = helper.util().formatHouseInfo(text);
        chooseDialog = new ProspectSelectHouseTypeDialog(this, selectHouseUsage,info,residences,residencet,residencew,residencec,apartments,apartmentt,apartmentw,apartmentc,villas,villat,villaw,villac);
        chooseDialog.show();
        chooseDialog.setListener(result -> {
            final int roomNum = result.get(ProspectSelectHouseTypeDialog.KEY_ROOM);
            final int drawingNum = result.get(ProspectSelectHouseTypeDialog.KEY_DRAWING_ROOM);
            final int kitchenNum = result.get(ProspectSelectHouseTypeDialog.KEY_KITCHEN);
            final int toiletNum = result.get(ProspectSelectHouseTypeDialog.KEY_TOILET);
            //当室厅厨卫四项，其中的每一项的房间数比之前所存储的房间数减少时，提示用户户型有所改变，会删除之前的所有图片
            if (roomNum < oldRoomNum || drawingNum<oldDrawingNum || toiletNum<oldToiletNum || kitchenNum<oldKitchenNum){
                if (commonDialog != null){
                    commonDialog.dismiss();
                    commonDialog = null;
                }
                commonDialog = new CommonDialog(mContext,"警告","您选择的户型有所改变，将会删除之前的所有图片，是否确定？"
                        ,"删除","取消");
                commonDialog.show();
                commonDialog.setConfirmListener(() -> {
                    //删除数据源中的所有数据
                    if (tempSource!=null)
                        tempSource.clear();
                    String canonical = helper.util().formatHouseInfo(roomNum, drawingNum, toiletNum, kitchenNum).toString();
                    houseType = canonical;
                    binding.chooseHouseTypeValueTextView.setTag(canonical);
                    String value = helper.util().formatHouseInfo(roomNum, drawingNum, toiletNum, kitchenNum).toText();
                    binding.chooseHouseTypeValueTextView.setText(value);
                });
                commonDialog.setCancelListener(() -> {
                    String canonical = helper.util().formatHouseInfo(oldRoomNum, oldDrawingNum, oldToiletNum, oldKitchenNum).toString();
                    houseType = canonical;
                    binding.chooseHouseTypeValueTextView.setTag(canonical);
                    String value = helper.util().formatHouseInfo(oldRoomNum, oldDrawingNum, oldToiletNum, oldKitchenNum).toText();
                    binding.chooseHouseTypeValueTextView.setText(value);
                });
                return;
            }
            String canonical = helper.util().formatHouseInfo(roomNum, drawingNum, toiletNum, kitchenNum).toString();
            houseType = canonical;
            binding.chooseHouseTypeValueTextView.setTag(canonical);
            String value = helper.util().formatHouseInfo(roomNum, drawingNum, toiletNum, kitchenNum).toText();
            binding.chooseHouseTypeValueTextView.setText(value);
        });
    }
    //endregion

    @Override
    protected void onActivityResult(int requestCode, int resultCode, Intent data) {
        super.onActivityResult(requestCode, resultCode, data);
        if (resultCode== Activity.RESULT_OK){
            if (requestCode==20){
                setResult(Activity.RESULT_OK);
                finish();
            }
        }
    }
}
